<?php
namespace app\index\controller;

use app\index\model\user as UserModel;
use app\index\model\expert as ExpertModel;

class User 
{
    public function getUserInfo($userToken)
    {
        //定义返回结果为数组
        $res = array();
        $note = UserModel::get(["userToken" => $userToken]);
        if ($note == NULL) {
            $res["avatarUrl"] = "";
            $res["nickName"] = "";
        }
        else {
            if ($note["isExpert"]) {
                //是专家，返回专家的姓名和消息
                $expertNote = ExpertModel::get(["expertToken" => $userToken]);
                $res["avatarUrl"] = $expertNote["realPhoto"];
                $res["nickName"] = $expertNote["realName"];
            }
            else {
                $res["avatarUrl"] = $note["userAvatar"];
                $res["nickName"] = $note["userName"];
            }
        }
        return $res;
    }
    public function saveUser($user) 
    {
        $message = "";
        if (UserModel::get(['userToken' => $user["userToken"]]) == NULL) {
            //该用户不存在，注册
            if ($user->isUpdate(false)->save()) {
                $message .= "add user success.";
            }
            else {
                $message .= "add user fail(not change).";
            }
        }
        else {
           
            //该用户存在，更新
            $updateUser = UserModel::get(["userToken" => $user["userToken"]]);
            $user = $user->toArray();
            foreach ($user as $key => $value) {
                $updateUser[$key] = $value;
            }
            if ($updateUser->save()) {
                $message .= "update user success.";
            }
            else {
                $message .= "update user fail(not change).";
            }
        }
        return $message;
    }
}